package cn.edu.java.io.inputstream;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipedInputStreamDemo {

    // 生产者线程
    static class Producer implements Runnable {
        private PipedOutputStream pipedOutputStream;

        public Producer(PipedOutputStream pipedOutputStream) {
            this.pipedOutputStream = pipedOutputStream;
        }

        @Override
        public void run() {
            try {
                // 向管道写入数据
                String message = "Hello, World!";
                pipedOutputStream.write(message.getBytes());
                System.out.println("Send message: " + message);
                pipedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 消费者线程
    static class Consumer implements Runnable {
        private PipedInputStream pipedInputStream;

        public Consumer(PipedInputStream pipedInputStream) {
            this.pipedInputStream = pipedInputStream;
        }

        @Override
        public void run() {
            try {
                // 从管道读取数据
                byte[] buffer = new byte[1024];
                int bytesRead = pipedInputStream.read(buffer);
                String message = new String(buffer, 0, bytesRead);
                System.out.println("Received message: " + message);
                pipedInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        try {
            // 创建PipedInputStream和PipedOutputStream对象
            PipedInputStream pipedInputStream = new PipedInputStream();
            PipedOutputStream pipedOutputStream = new PipedOutputStream();

            // 将输入流和输出流连接起来
            pipedInputStream.connect(pipedOutputStream);

            // 创建生产者线程和消费者线程
            Thread producerThread = new Thread(new Producer(pipedOutputStream));
            Thread consumerThread = new Thread(new Consumer(pipedInputStream));

            // 启动线程
            producerThread.start();
            consumerThread.start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

